//
//  xmltestViewController.m
//  xmltest
//
//  Created by easystudio on 7/3/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "XmlParser.h"
#import "XmlRequestBody.h"
#import "HttpServerURL.h"


#define METHOD_CALL         @"methodCall"
#define METHOD_NAME         @"methodName"
#define METHOD_RESPONSE     @"methodResponse"
#define PARAMS              @"params"
#define PARAM               @"param"
#define FAULT               @"fault"
#define FAULT_CODE          @"faultCode"
#define FAULT_STRING        @"faultString"

#define TYPE_INT            @"int"
#define TYPE_I4             @"i4"
#define TYPE_I8             @"i8"
#define TYPE_EX_I8          @"ex:i8"
#define TYPE_DOUBLE         @"double"
#define TYPE_BOOLEAN        @"boolean"
#define TYPE_STRING         @"string"
#define TYPE_DATE_TIME_ISO8601 @"dateTime.iso8601"
#define TYPE_BASE64         @"base64"
#define TYPE_ARRAY          @"array"
#define TYPE_STRUCT         @"struct"

#define DATETIME_FORMAT     @"yyyyMMdd'T'HH:mm:ss"
#define EXP_NULL            @"ex:nil"


//NSString *tmpstring = @"";
bool isequal = YES;

static ASIFormDataRequest *request;

@implementation XmlParser

@synthesize mydata;
//@synthesize xmlParser;
//@synthesize   nextnode;
//@synthesize topicdata, topicstruct;
//@synthesize test;



//@synthesize node, prenode, valuetype, keyindex, keyvalue;


- (id)init
{
    
	self = [super init];
	if(self)
	{
        m_condition = [[NSCondition alloc]init];
        //xmlbody = [[XmlRequestBody alloc] init];
		topicdata = [[NSMutableDictionary alloc] initWithCapacity:0];
		//topicstruct = [[NSMutableDictionary alloc] initWithCapacity:20];
        topicstruct = [[NSMutableArray alloc] initWithCapacity:0];
        //test = [[NSMutableDictionary alloc] init];
        node =  [[NSMutableString alloc] initWithCapacity:0];
        prenode =  [[NSMutableString alloc] initWithCapacity:0];
        valuetype =  [[NSMutableString alloc] initWithCapacity:0];
        keyindex =  [[NSMutableString alloc] initWithCapacity:0]; 
        keyvalue =  [[NSMutableString alloc] initWithCapacity:0];
        tmp = [[NSMutableString alloc] initWithCapacity:0];
        
        mydata = [[NSMutableData alloc] initWithCapacity:0];
        return_mystring = [[NSString alloc] init];
        
	}
    if (request == nil) {
         request = [[ASIFormDataRequest alloc] init];
    }

	return self;
}



//#define urlAddress @"http://172.16.15.6/xmlrpc"
#define timeOut 15
#define httpMethod @"POST"


-(int)SendXml:(NSString *)body
{    
    [self init];
    [body retain];
        
    @try 
    {
        [m_condition lock];
        
        NSURL *httpsURL = [NSURL URLWithString:[HttpServerURL GetInstance].serverURL];
        ASIFormDataRequest * tempRequest = [[ASIFormDataRequest alloc] initWithURL:httpsURL];
        [tempRequest setURL:httpsURL];
        
        //超时时间
        tempRequest.timeOutSeconds = 30;
        [tempRequest setRequestMethod:@"POST"];
        [tempRequest setPostBody:[NSData dataWithData:[body dataUsingEncoding:NSUTF8StringEncoding]]];
        
        //开始执行
        if (request != nil){
            [tempRequest setRequestCookies:[request requestCookies]];
        }
        [tempRequest setValidatesSecureCertificate:NO];
        [tempRequest startSynchronous];
        
        NSError* error = [tempRequest error];
        if (!error) 
        {
            NSData *data = [tempRequest responseData];
            mydata = [NSMutableData dataWithData:data];
            request = tempRequest;
        } 
        else
        {
            NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
        }
        
        NSString *theXML=[[NSString alloc]  
                          initWithBytes:[mydata mutableBytes]  
                          length:[mydata length]
                          encoding:NSUTF8StringEncoding];
        
        [theXML release];
        if(xmlParser){
            [xmlParser release];
        }
        
        
        NSString *mydatastring = [[NSString alloc ] initWithData:mydata encoding:NSUTF8StringEncoding];
        NSLog(@"mydata is :%@",mydatastring );
        [mydatastring release];
        
        xmlParser=[[NSXMLParser alloc] initWithData:mydata];
        [xmlParser setDelegate:self];
        [xmlParser setShouldResolveExternalEntities:YES];
        [xmlParser parse];
        
        [body release];
        
    }
    @catch (NSException *exception) 
    {
        NSLog(@"Caught %@%@", [exception name], [exception reason]);
        return 0;
    }
    return 1;
    
}

//
-(int)SendXmlNoFilter:(NSString *)body
{
    [self init];
    [body retain];
    @try 
    { 
        //setting params
        NSURL *httpsURL = [NSURL URLWithString:[HttpServerURL GetInstance].serverUrlNoFilter];
        ASIFormDataRequest *tempRequest = [[ASIFormDataRequest alloc] initWithURL:httpsURL];
        [tempRequest setURL:httpsURL];
        
        //超时时间
        tempRequest.timeOutSeconds = 30;
        [tempRequest setRequestMethod:@"POST"];
        [tempRequest setPostBody:[NSData dataWithData:[body dataUsingEncoding:NSUTF8StringEncoding]]];
        
        //开始执行
        [tempRequest setValidatesSecureCertificate:NO];
        [tempRequest startSynchronous];
        NSError* error = [tempRequest error];
        
        if (!error) 
        {
            NSData *data = [tempRequest responseData];
            mydata = [NSMutableData dataWithData:data];
            request = tempRequest;
        } 
        else
        {
            NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
            //NSLog(@"[email=%@]%@",[error[/email], userInfo]);
//            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:@"请检查是否连接网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil , nil];
//            [alert show];
//            [alert release];

        }
        
        NSString *theXML=[[NSString alloc]  
                          initWithBytes:[mydata mutableBytes]  
                          length:[mydata length]
                          encoding:NSUTF8StringEncoding];
        
        [theXML release];
        if(xmlParser){
            [xmlParser release];
        }
    
        NSString *mydatastring = [[NSString alloc ] initWithData:mydata encoding:NSUTF8StringEncoding];
        NSLog(@"mydata is :%@",mydatastring );
        [mydatastring release];
        xmlParser=[[NSXMLParser alloc] initWithData:mydata];
        [xmlParser setDelegate:self];
        [xmlParser setShouldResolveExternalEntities:YES];
        [xmlParser parse];
        [body release];
    }
    @catch (NSException *exception) 
    {
        NSLog(@"Caught %@%@", [exception name], [exception reason]);
        return 0;
    }
    return 1;
    
}

//SendXmlGetSubURL
-(NSString *)SendXmlGetSubURL:(NSString *)company_code
{
    [self init];
    [company_code retain];
    
    //setting params
    NSLog(@"portalURL=%@", [HttpServerURL GetInstance].portalURL);
    NSString *tmp_url=[NSString stringWithFormat:@"%@%@",[HttpServerURL GetInstance].portalURL,company_code];
    NSURL *portalURL = [NSURL URLWithString:tmp_url];
    ASIHTTPRequest *request1=[[ASIHTTPRequest alloc] initWithURL:portalURL];
    
    //超时时间
    request1.timeOutSeconds = 30;
    
    [request1 setRequestMethod:@"GET"];
    //开始执行
    [request1 startSynchronous];
    NSError* error = [request1 error];
    
    if (!error) {
        NSData *data = [request1 responseData];
        mydata = [NSMutableData dataWithData:data];
    } 
    else{
        NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
    }
    
    NSString *mydatastring = [[NSString alloc ] initWithData:mydata encoding:NSUTF8StringEncoding];
    NSLog(@"mydata is :%@",mydatastring );

    return_mystring = [[NSString alloc ] initWithData:mydata encoding:NSUTF8StringEncoding];
    NSLog(@"mydata is :%@",return_mystring );

//    [request1 release];
    [company_code release];
    return return_mystring;
    
}

//解析xml返回array
-(int)XmlToArray:(NSData *)xmlData
{
    if(xmlParser){
        [xmlParser release];
    }
    
    xmlParser=[[NSXMLParser alloc] initWithData:xmlData];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
    
    return 1;
}

//执行成功
- (void)requestDidSuccess:(ASIFormDataRequest *)request
{
}
//执行失败
- (void)requestDidFailed:(ASIFormDataRequest *)request
{
   
}
-(NSMutableArray *)GetReturnArray
{
    return topicstruct;
    //return self.topicstruct;      //modified by 1021
}


#pragma mark  deal xml


-(void)connection:(NSURLConnection *)connection
   didReceiveData:(NSData *)data{
    //NSLog(@"it is didReceivedata:111111");
    [mydata appendData:data];

}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //NSLog(@"it is didReceiveResponse:22222");
    //NSLog(@"mydata length is :%d",[mydata length]);
    [mydata setLength:0];
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //NSLog(@"ERROR with theConnection");
    [connection release];
    [mydata
     release];
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //NSLog(@"it is connectionDidFinishLoading:33333");
    NSString *theXML=[[NSString alloc]  
                      initWithBytes:[mydata mutableBytes]  
                      length:[mydata length]
                      encoding:NSUTF8StringEncoding];
    
    [theXML release];
    if(xmlParser){
        [xmlParser release];
    }
    
    NSString *mydatastring = [[NSString alloc ] initWithData:mydata encoding:NSUTF8StringEncoding];
    //NSLog(@"mydata is :%@",mydatastring );
    [mydatastring release];
    
    xmlParser=[[NSXMLParser alloc] initWithData:mydata];
    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:YES];
    [xmlParser parse];
    
    [connection release];
}


-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName  
   attributes:(NSDictionary *)attributeDict{
    //NSLog(@"it is didStartElement,44444");
    //NSLog(@"didstartelement's elementname :%@", elementName);
    
    if ([elementName isEqualToString:@"fault"])
    {
        //fail;
    }
    
    //判断是否name和value节点，以便获取数据    
    if ([elementName isEqualToString:@"name"]||[elementName isEqualToString:@"value"]||[elementName isEqualToString:@"member"]) 
    {
        [node setString:elementName];
        
    }
    if ([elementName isEqualToString:@"param"]||[elementName isEqualToString:@"struct"]||[elementName isEqualToString:@"array"]) {
        [prenode setString:elementName];
        
    }

    
    //判断value节点类型
    if ([node isEqualToString:@"value"]) {
        if ([elementName isEqualToString:TYPE_INT]||[elementName isEqualToString:TYPE_I4]||[elementName isEqualToString:TYPE_I8]||[elementName isEqualToString:TYPE_EX_I8]) {
            [valuetype setString:@"long"];
        }
        if ([elementName isEqualToString:TYPE_DOUBLE]) {
            [valuetype setString:@"double"];
        }
        if ([elementName isEqualToString:TYPE_BOOLEAN]) {
            [valuetype setString:@"bool"];
        }
        if ([elementName isEqualToString:TYPE_DATE_TIME_ISO8601]) {
            [valuetype setString:@"date"];
        }
        if ([elementName isEqualToString:EXP_NULL]) {
            [valuetype setString:@"nil"];
        }

    }
     
    
    
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
   // NSLog(@"it is foundCharacters:%@,55555", string);
    /*
    if ([node isEqualToString:@"name"]) {
        [memberdata setObject:string forKey:@"name"];
    }
    if ([node isEqualToString:@"value"]) {
        [memberdata setObject:string forKey:@"value"];
    }
     */
    if ([node isEqualToString:@"name"]) {
        [keyindex setString:string];
        isequal = NO;     
        [tmp setString:@""];
    }else{
    if ([node isEqualToString:@"value"]) {
        [keyvalue setString:string];
        isequal = YES;
        //[self GetValue:string type:valuetype];
    }else
    {
        [keyvalue setString:string];
        isequal = YES;
    }
    }
    
    //deal for solve &lt &gt 
    if (isequal == YES) {
        if (![keyvalue isEqualToString:keyindex]) {
            //tmpstring = [NSString stringWithFormat:@"%@%@" ,tmpstring, keyvalue];
            [tmp appendString:keyvalue];
            [keyvalue setString:tmp];
        }
    }


}

/*
-(id)GetValue:(NSString *)string type:(NSString *)type
{
    if ([valuetype isEqualToString:@"long"]) {
        keyvalue = [string longValue];
    }
    if ([valuetype isEqualToString:@"double"]) {
        //keyvalue = [string doubleValue];
    }
    if ([valuetype isEqualToString:@"bool"]) {
        if ([string isEqualToString:@"true"])    keyvalue = [1 boolValue];   //YES
        else    keyvalue = [0 boolValue];   //NO
    }
    if ([valuetype isEqualToString:@"date"]) {
        
    }
   
    
}
*/

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
     //NSLog(@"it is didEndElement,666666");
    if ([valuetype isEqualToString:@"nil"]) {
        [keyvalue setString:@""];
    }
    
    if (keyindex == nil) {
        [keyindex setString:@""];
    }
    if (keyvalue == nil) {
        [keyvalue setString:@""];
    }
    
    if ([elementName isEqualToString:@"member"]) {
        //NSString *tmpkeyvalue = [NSString stringWithFormat:@"%@",keyvalue]; 
        NSString *tmpkeyvalue = [[NSString alloc ] initWithFormat:@"%@",keyvalue];  //modified 1021
        [topicdata setObject:tmpkeyvalue forKey:keyindex];
        [tmpkeyvalue release];
        //NSLog(@"keyvalue:%@, node:%@",tmpkeyvalue,keyindex);
        //NSLog(@"%@",[topicdata objectForKey:keyindex]);
        [node setString:@""];
        [keyvalue setString:@""];
        [keyindex setString:@""];
        [valuetype setString:@""];  //added 07-23
        
    }
    if ([elementName isEqualToString:prenode]) {
        
        //if (topicdata!=nil) {
        if ([topicdata count]>0) {
            NSMutableDictionary *testdata = [[NSMutableDictionary alloc] initWithDictionary:topicdata];
            [topicstruct addObject:testdata];
            [testdata release];
            //[topicstruct addObject:@"aa"];
            
            //NSLog(@" struct count:%i",[topicstruct count]);
            [prenode setString:@""];
            [topicdata removeAllObjects];
        }
        else{   
            
            if ([keyvalue isEqualToString:@"0"]||[keyvalue isEqualToString:@"1"]||[keyvalue isEqualToString:@"-1"]) {
                
            //when return a flag,0 or 1; 
            //NSLog(@"keyvalue:%@", keyvalue);
            

            [topicdata setObject:[NSString stringWithFormat:@"%@",keyvalue] forKey:@"flag"];
            //for (id key in topicdata){
            //    NSLog(@"key:%@;value:%@", key,[topicdata objectForKey:@"flag"]);
            //}

            NSMutableDictionary *testdata = [[NSMutableDictionary alloc] initWithDictionary:topicdata];
            [topicstruct addObject:testdata];
            [testdata release];
            //[topicstruct addObject:topicdata];
            [node setString:@""];
            [keyvalue setString:@""];
            [keyindex setString:@""];
            [prenode setString:@""];
            [valuetype setString:@""];  //added 07-23
            [topicdata removeAllObjects];
            }
            else{
                //topicstruct = nil;
                //added by tongyf  20120117
                if (keyvalue != nil && ([keyvalue isEqualToString:@""]==NO)) {
                    [topicdata setObject:[NSString stringWithFormat:@"%@",keyvalue] forKey:@"param"];
                    NSMutableDictionary *testdata = [[NSMutableDictionary alloc] initWithDictionary:topicdata];
                    [topicstruct addObject:testdata];
                    [testdata release];
                    [node setString:@""];
                    [keyvalue setString:@""];
                    [keyindex setString:@""];
                    [prenode setString:@""];
                    [valuetype setString:@""];  //added 07-23
                    [topicdata removeAllObjects];
                }
                
            }
        }
    }
}

-(void)parserDidStartDocument:(NSXMLParser *)parser{
    //[self init];

    //NSLog(@"it is parserDidStartDocument,777777");
    //[activityIndicatorView ];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
    //NSLog(@"it is parserDidEndDocument,88888");
    NSLog(@"count:%d",[topicstruct count]);
    /*
    NSMutableDictionary *print =  [[NSMutableDictionary alloc] init];
        print = [topicstruct objectAtIndex:0];
        NSLog(@"memberid:%@",[print objectForKey:@"member_id"]);    
    [print release];
    */ 
    
}



- (void)dealloc
{
    self.mydata = nil;
    //[xmlParser release];
        
    [prenode release];
    [node release];
    [valuetype release];
    [keyindex release];
    [keyvalue release];
    
    [topicdata release];
    [topicstruct release];
    [tmp release];
    
//    if (request != nil){
//        [request release];
//    }
    
    //[xmlbody release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
